import React, { Component } from 'react'
import classNames from 'classnames'
export default class TodoItem extends Component {
  state = {
    currentId: '',
    currentName: '',
  }
  inputRef = React.createRef()
  render() {
    const { item } = this.props
    return (
      <li
        //'editing'
        className={classNames({
          completed: item.checked,
          editing: item.id === this.state.currentId,
        })}
        key={item.id}
      >
        <div className="view">
          <input
            className="toggle"
            type="checkbox"
            checked={item.checked}
            onChange={() => {
              this.ChangeTodo(item.id)
            }}
          />
          <label
            onDoubleClick={() => {
              this.showEdit(item)
            }}
          >
            {item.name}
          </label>
          <button
            className="destroy"
            onClick={() => {
              this.DelTodo(item.id)
            }}
          ></button>
        </div>
        <input
          className="edit"
          value={this.state.currentName}
          onChange={(e) => {
            this.setState({ currentName: e.target.value })
          }}
          onKeyUp={this.EditTodo}
          onBlur={() => this.setState({ currentId: '' })}
          ref={this.inputRef}
        />
      </li>
    )
  }
  //删除事件
  DelTodo = (id) => {
    // console.log('id', id)
    this.props.DelTodoById(id)
  }

  //切换勾选是否完成
  ChangeTodo = (id) => {
    this.props.ChangeTodoDyId(id)
  }

  //双击调出编辑框
  showEdit = ({ id, name }) => {
    // console.log(id)
    this.setState(
      {
        currentId: id,
        currentName: name,
      },
      () => {
        this.inputRef.current.focus()
      }
    )
  }

  //当按下enter键时提交编辑，当按下esc时取消编辑
  EditTodo = (e) => {
    // console.log(e.keyCode)
    if (e.keyCode === 27) {
      this.setState({
        currentId: '',
        currentName: '',
      })
    } else if (e.keyCode === 13) {
      this.props.EditTodo(this.state.currentId, this.state.currentName)
      this.setState({
        currentId: '',
        currentName: '',
      })
    }
  }
}
